<template>
  <div>
    <el-card class="box-card" style="width: 80%; margin: 20px auto">
      <div slot="header" class="clearfix">
        <span>选择销售属性</span>
        <el-form ref="saleform" :model="dataForm">
          <el-form-item
            v-for="(attr, aidx) in saleAttrs"
            :label="attr.name"
            :key="attr.id"
          >
            <el-input
              v-model="dataForm.tempSaleAttrs[aidx].attrId"
              type="hidden"
              v-show="false"
            ></el-input>
            <el-checkbox-group
              v-model="dataForm.tempSaleAttrs[aidx].attrValues"
            >
              <el-checkbox
                v-for="val in saleAttrs[aidx].valueSelect.split(';')"
                :label="val"
                :key="val"
              ></el-checkbox>
              <div style="margin-left: 20px; display: inline">
                <el-button
                  v-show="!inputVisible[aidx].view"
                  class="button-new-tag"
                  size="mini"
                  @click="showInput(aidx)"
                  >+自定义</el-button
                >
                <el-input
                  v-show="inputVisible[aidx].view"
                  v-model="inputValue[aidx].val"
                  :ref="'saveTagInput' + aidx"
                  size="mini"
                  style="width: 150px"
                  @keyup.enter.native="handleInputConfirm(aidx)"
                  @blur="handleInputConfirm(aidx)"
                ></el-input>
              </div>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </div>
      <el-button type="primary" @click="submitBack">上一步</el-button>
      <el-button type="success" @click="submitStep"
        >下一步：设置SKU信息</el-button
      >
    </el-card>
  </div>
</template>

<script>
import AttrApi from "@/api/product/attribute";

export default {
  data() {
    return {
      saleAttrs: [],
      dataForm: {
        tempSaleAttrs: [],
      },
      inputVisible: [],
      inputValue: [],
      tableAttrColumn: [],
    };
  },
  methods: {
    init(id) {
      AttrApi.getListByCate({
        categoryId: id,
        attrType: 0,
      }).then(({ data }) => {
        //先对表单的baseAttrs进行初始化
        data.forEach((attr) => {
          this.dataForm.tempSaleAttrs.push({
            attrId: attr.id,
            attrValues: [],
            attrName: attr.name,
          });
          this.inputVisible.push({ view: false });
          this.inputValue.push({ val: "" });
        });
        this.saleAttrs = data;
      });
    },
    showInput(idx) {
      this.inputVisible[idx].view = true;
    },
    handleInputConfirm(idx) {
      let inputValue = this.inputValue[idx].val;
      if (inputValue) {
        if (this.saleAttrs[idx].valueSelect == "") {
          this.saleAttrs[idx].valueSelect = inputValue;
        } else {
          this.saleAttrs[idx].valueSelect += ";" + inputValue;
        }
      }
      this.inputVisible[idx].view = false;
      this.inputValue[idx].val = "";
    },
    submitStep() {
      //根据笛卡尔积运算进行生成sku
      let selectValues = [];
      this.tableAttrColumn = [];
      this.dataForm.tempSaleAttrs.forEach((item) => {
        if (item.attrValues.length > 0) {
          this.tableAttrColumn.push(item);
          selectValues.push(item.attrValues);
        }
      });
      let descartes = this.descartes(selectValues);
      //[["黑色","6GB","移动"],["黑色","6GB","联通"],["黑色","8GB","移动"],["黑色","8GB","联通"],
      //["白色","6GB","移动"],["白色","6GB","联通"],["白色","8GB","移动"],["白色","8GB","联通"],
      //["蓝色","6GB","移动"],["蓝色","6GB","联通"],["蓝色","8GB","移动"],["蓝色","8GB","联通"]]
      //console.log("生成的组合", JSON.stringify(descartes));
      //有多少descartes就有多少sku
      let skus = [];

      descartes.forEach((descar, descaridx) => {
        let attrArray = []; //sku属性组
        descar.forEach((de, index) => {
          //构造saleAttr信息
          let saleAttrItem = {
            attrId: this.tableAttrColumn[index].attrId,
            attrName: this.tableAttrColumn[index].attrName,
            attrValue: de,
          };
          attrArray.push(saleAttrItem);
        });
        //descaridx，判断如果之前有就用之前的值;
        skus.push({
          attr: attrArray,
          skuName: descar.join(" "),
          skuTitle: descar.join(" "),
          descar: descar,
        });
      });

      this.$emit("submitData", skus);
    },
    submitBack() {
      this.$emit("backStep", 1);
    },
    //笛卡尔积运算
    descartes(list) {
      //parent上一级索引;count指针计数
      var point = {};

      var result = [];
      var pIndex = null;
      var tempCount = 0;
      var temp = [];
      //根据参数列生成指针对象
      for (var index in list) {
        if (typeof list[index] == "object") {
          point[index] = { parent: pIndex, count: 0 };
          pIndex = index;
        }
      }
      //单维度数据结构直接返回
      if (pIndex == null) {
        return list;
      }
      //动态生成笛卡尔积
      while (true) {
        for (var index in list) {
          tempCount = point[index]["count"];
          temp.push(list[index][tempCount]);
        }

        //压入结果数组
        result.push(temp);
        temp = [];

        //检查指针最大值问题
        while (true) {
          if (point[index]["count"] + 1 >= list[index].length) {
            point[index]["count"] = 0;
            pIndex = point[index]["parent"];
            if (pIndex == null) {
              return result;
            }

            //赋值parent进行再次检查
            index = pIndex;
          } else {
            point[index]["count"]++;
            break;
          }
        }
      }
    },
  },
};
</script>
